<template>
  <el-form ref="formRef" :model="formData" label-width="120px">
    <base-layout visibleContent2>
      <template #searchPanel>
        <el-tabs v-model="activeTab">
          <el-tab-pane name="returnInfo" label="退货基础信息">
            <el-row>
              <el-col :span="6">
                <el-form-item label="退货编号" prop="returnCode">
                  <el-input
                    v-model="formData.returnCode"
                    readonly="readonly"
                    disabled
                    placeholder="自动生成"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="退货门店" prop="storeId">
                  <job-shop
                    v-model="formData.storeId"
                    defaultStoreId
                    class="w-100"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="退货类型" prop="returnType">
                  <el-select
                    v-model="formData.returnType"
                    placeholder="请选择"
                    class="w-100"
                  >
                    <el-option
                      v-for="item in dict['退货类型']"
                      :key="item.index"
                      :value="item.value"
                      :label="item.text"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购单号" prop="purchaseCode">
                  <el-input
                    placeholder="请输入"
                    v-model="formData.purchaseCode"
                    @blur="purchaseCodeBlur"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="单据日期" prop="receiptsTime">
                  <el-date-picker
                    v-model="formData.receiptsTime"
                    type="datetime"
                    disabled
                    placeholder="请选择"
                    class="w-100"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="退货供应商" prop="returnSupplierId">
                  <el-select
                    v-model="formData.returnSupplierId"
                    @change="supplierChange"
                    placeholder="请选择"
                    class="w-100"
                  >
                    <el-option
                      v-for="item in supplierList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.supplierName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="供应商联系人" prop="supplierUserName">
                  <el-input
                    placeholder="请输入"
                    v-model="formData.supplierUserName"
                    readonly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="供应商联系方式" prop="supplierPhone">
                  <el-input
                    placeholder="请输入"
                    v-model="formData.supplierPhone"
                    readonly
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="18">
                <el-form-item label="退货备注" prop="remark">
                  <el-input
                    v-model="formData.remark"
                    type="textarea"
                    :rows="6"
                    placeholder="请输入"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane
            v-if="formData.returnType == '采购退货'"
            name="applyInfo"
            label="采购信息"
          >
            <el-row>
              <el-col :span="6">
                <el-form-item label="采购编号">
                  <span class="detail-vlaue">{{ purchaseDetail.code }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购门店">
                  <span class="detail-vlaue">{{
                    purchaseDetail.storeName
                  }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购供应商">
                  <span class="detail-vlaue">{{
                    purchaseDetail.purchaseSupplierName
                  }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购类型">
                  <span class="detail-vlaue">{{ purchaseDetail.type }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="单据日期">
                  <span class="detail-vlaue">{{
                    purchaseDetail.receiptsTime
                  }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="供应商联系人">
                  <span class="detail-vlaue">{{
                    purchaseDetail.supplierUserName
                  }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="供应商联系方式">
                  <span class="detail-vlaue">{{
                    purchaseDetail.supplierPhone
                  }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="采购备注">
                  <span class="detail-vlaue">{{ purchaseDetail.remark }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template #contentPanel>
        <template v-if="activeTab == 'returnInfo'">
          <el-row>
            <el-col :span="12">退货负责人员</el-col>
          </el-row>
          <el-divider></el-divider>
          <el-row>
            <el-col :span="6">
              <el-form-item label="退货负责人" prop="userName">
                <user-select
                  v-model="formData.userName"
                  :store-id="formData.storeId"
                  @change="userNameHChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系方式" prop="phone">
                <el-input placeholder="请输入" v-model="formData.phone" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template v-else>
          <el-row>
            <el-col :span="12">采购人员</el-col>
          </el-row>
          <el-divider></el-divider>
          <el-row>
            <el-col :span="6">
              <el-form-item label="采购人员">
                <span class="detail-vlaue">{{ purchaseDetail.userName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系方式">
                <span class="detail-vlaue">{{ purchaseDetail.phone }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </template>
      <template #contentPanel2>
        <template v-if="activeTab == 'returnInfo'">
          <el-row type="flex" align="middle">
            <el-col :span="12">退货精品列表</el-col>
            <el-col class="text-right" :span="12"> </el-col>
          </el-row>
          <el-divider></el-divider>
          <data-table
            has-action
            :is-show-page="false"
            :value="formData.partsList"
            :table-column-attributes="tableColumns"
            :width="160"
          >
            <template #action="{row, $index}">
              <i
                class="el-icon-delete"
                title="删除"
                style="cursor: pointer;"
                @click="handleDataDelete(row, $index)"
              ></i>
            </template>
            <div class="total-count" slot="allNum">
              精品总金额:<span class="money-value"
                >￥{{ formData.amount }}</span
              >
              <span class="ml-20">精品总数:</span
              ><span class="count-value">{{ formData.partsNum }}</span>
            </div>
          </data-table>
          <div class="text-right mt-10">
            <span class="total-count">
              总金额:<span class="money-value">￥{{formData.amount}}</span>
            </span>
            <el-button v-permission="$route.params.id == 0 ? authConfig.add : authConfig.edit" class="ml-20" type="success" @click="submitHandle"
              >{{$route.params.id == 0 ? '新增' : '更新'}}退货单</el-button
            >
          </div>
        </template>
        <template v-else>
          <el-row type="flex" align="middle">
            <el-col :span="12">采购精品列表</el-col>
          </el-row>
          <el-divider></el-divider>
          <data-table
            :has-action="false"
            :is-show-page="false"
            :value="purchaseDetail.partsList || []"
            :table-column-attributes="tableColumns2"
            :width="160"
          >
          </data-table>
        </template>
      </template>
      <template #dialog> </template>
    </base-layout>
  </el-form>
</template>

<script>
import BaseLayout from '@/views/layout/Base'
import DataTable from '@/components/DataTable'
import { JobShop } from '@/components/index'
import UserSelect from '@/components/CommonForm/UserSelect'
import { getDict, parseTimeToYMDHMS } from '@/utils'
import {
  getSupplierByStorId,
  details
} from '@/api/after-sale/systemManage/supplier'

import {
  save,
  update,
  editDetailById,
  getPurchaseCode,
  findSourceCode
} from '@/api/pre-sale/boutiquePurchase/return'

export default {
  components: { JobShop, BaseLayout, DataTable, UserSelect },
  data() {
    this.authConfig = {
      add: 'purchaseReturn:save',
      edit: 'purchaseReturn:update'
    }

    this.tableColumns2 = [
      { name: '精品编号', value: 'partsCode', type: 'text' },
      { name: '精品名称', value: 'partsName', type: 'text' },
      { name: '一级类别', value: 'partsType', type: 'text' },
      { name: '二级类别', value: 'partsUnit', type: 'text' },
      { name: '采购数量', value: 'purchaseNum', type: 'text' },
      { name: '采购单价', value: 'purchasePrice', type: 'text' },
      { name: '优惠', value: 'freePrice', type: 'text' },
      { name: '总金额', value: 'amount', type: 'text' }
    ]

    return {
      formData: {
        returnCode: '',
        storeId: '',
        returnType: '',
        purchaseCode: '',
        receiptsTime: parseTimeToYMDHMS(new Date()),
        returnSupplierId: '',
        supplierUserName: '',
        supplierPhone: '',
        remark: '',
        userName: '',
        phone: '',
        amount: '', // 总金额
        partsNum: 0, // 配件总数量
        freePrice: '', // 优惠总金额
        partsList: []
      },
      tableColumns: [
        { name: '精品编号', value: 'partsCode', type: 'text' },
        { name: '精品名称', value: 'partsName', type: 'text' },
        { name: '一级类别', value: 'partsType', type: 'text' },
        { name: '二级类别', value: 'partsUnit', type: 'text' },
        {
          name: '退货数量',
          value: 'returnNum',
          type: 'inputNumber',
          maxFiledName: 'num',
          action: this.calcData
        },
        { name: '采购成本', value: 'returnPrice', type: 'text' },
        { name: '优惠', value: 'freePrice', type: 'text' },
        { name: '总金额', value: 'amount', type: 'text' }
      ],
      detail: {},
      purchaseDetail: {},
      supplierList: [],
      activeTab: 'returnInfo'
    }
  },
  computed: {
    tableDataMap() {
      const map = {}
      this.formData.partsList.forEach((item, index) => {
        map[item.partsId] = index
      })
      return map
    },
    storeId() {
      return this.formData.storeId
    }
  },
  watch: {
    storeId() {
      this.requestSupplierList()
    }
  },
  methods: {
    purchaseCodeBlur() {
      const { returnType, purchaseCode } = this.formData
      if (returnType && purchaseCode) {
        findSourceCode(returnType, purchaseCode).then(res => {
          this.purchaseDetail = res.data

          this.formData.returnSupplierId = this.purchaseDetail.purchaseSupplierId
          this.formData.supplierUserName = this.purchaseDetail.supplierUserName
          this.formData.supplierPhone = this.purchaseDetail.supplierPhone

          const data = this.purchaseDetail.partsList || []
          if (data.length > 0) {
            const partsList = []
            data.forEach(item => {
              const num = item.purchaseNum || item.inStorageNum || 0
              const price = item.storagePrice || item.purchasePrice || 0

              partsList.push({
                amount: num * price,
                freePrice: item.freePrice,
                partsCode: item.partsCode,
                partsId: item.partsId,
                partsName: item.partsName,
                partsType: item.partsType,
                partsUnit: item.partsUnit,
                returnNum: num,
                returnPrice: price,
                num: num
              })
            })
            this.$nextTick(() => {
              this.formData.partsList = partsList
              this.calcCountData()
            })
          }
        })
      }
    },
    handleDataDelete(row, $index) {
      this.formData.partsList.splice($index, 1)
      this.calcCountData()
    },
    submitHandle() {
      const method = this.$route.params.id == 0 ? save : update
      this.$refs.formRef.validate(valid => {
        if (valid) {
          method(this.formData).then(res => {
            const length = this.$store.state.tagsView.visitedViews.length
            this.$store.dispatch('delVisitedViews', this.$route)
            if (length == 2) {
              this.$router.replace({ path: '/' })
            } else {
              this.$router.go(-1)
            }
          })
        }
      })
    },
    // 计算当前数据
    calcData(row) {
      const { returnPrice, returnNum, freePrice } = row
      row.amount = returnNum * returnPrice - freePrice
      this.calcCountData()
    },
    // 统计所有数据
    calcCountData() {
      let amount = 0 // 总金额
      let freePrice = 0 // 总金额
      let returnNum = 0 // 总数量

      this.formData.partsList.forEach(item => {
        amount += item.amount || 0
        freePrice += item.freePrice || 0
        returnNum += item.returnNum || 0
      })
      this.formData.amount = amount
      this.formData.freePrice = freePrice
      this.formData.partsNum = returnNum
    },
    // 供应商改变
    supplierChange(value) {
      this.formData.supplierUserName = ''
      this.formData.supplierPhone = ''
      this.requestSupplierDetail(value)
    },
    // 负责人选择
    userNameHChange(item) {
      this.formData.userName = item.userName
      this.formData.phone = item.phone
    },
    dialogClose() {
      this.dialogVisible = false
    },
    // 请求编辑采购详情
    requestEditDetail(id) {
      editDetailById(id).then(res => {
        console.log(res.data)
        this.formData = res.data
      })
    },
    // 请求编码
    requestPurchaseCode() {
      getPurchaseCode().then(res => {
        this.formData.returnCode = res.data
      })
    },
    // 请求 供应商
    requestSupplierList() {
      const { storeId } = this.formData
      if (!storeId) {
        return
      }

      getSupplierByStorId(this.storeId, '精品供应商').then(res => {
        this.supplierList = res.data || []
        if (!this.supplierList.find(item => item.id == this.formData.returnSupplierId)) {
          this.formData.returnSupplierId = ''
          this.formData.supplierUserName = ''
          this.formData.supplierPhone = ''
        }
      })
    },
    // 请求供应商详情
    requestSupplierDetail(id) {
      details(id).then(res => {
        this.formData.supplierUserName = res.data.contactName
        this.formData.supplierPhone = res.data.contactPhone
      })
    }
  },
  created() {
    this.dict = getDict(['退货类型'])
  },
  mounted() {
    const { id, returnType, purchaseCode } = this.$route.params
    this.formData.returnType = returnType
    this.formData.purchaseCode = purchaseCode == 0 ? '' : purchaseCode
    if (id != 0) {
      this.requestEditDetail(id)
    } else {
      this.requestPurchaseCode()
      this.purchaseCodeBlur()
    }
  }
}
</script>

<style></style>
